package com.xsystem.util;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TimerUtil {

	private static final Logger log = LoggerFactory.getLogger(TimerUtil.class);

	private String name;
	private String apiPath;
	private long startTime;
	private List<TimeElapsed> timeElapseds;

	public TimerUtil(String apiPath, String name) {
		this.apiPath = apiPath;
		this.name = name;
		this.startTime = getSystemTime();
		timeElapseds = new ArrayList<TimeElapsed>();
	}

	public void done() {
		long endTime = getSystemTime();
		timeElapseds.add(new TimeElapsed(name, endTime - startTime));
	}

	public void record() {
		log.debug(constructLog());
	}

	public void recordForTest() {
		System.out.println(constructLog());
	}

	private String constructLog() {
		JSONArray jsonArray = new JSONArray();
		for (TimeElapsed timeElapsed : timeElapseds) {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put(timeElapsed.getName(), timeElapsed.getElapsed());
			jsonArray.add(jsonObj);
		}

		JSONObject jsonObj = new JSONObject();
		jsonObj.put("api", apiPath);
		jsonObj.put("time", jsonArray);

		return jsonObj.toString();
	}

	public void reset() {
		this.startTime = getSystemTime();
	}

	public void reset(String name) {
		this.name = name;
		this.startTime = getSystemTime();
	}

	public void recordAndReset(String name) {
		this.done();
		this.reset(name);
	}

	private long getSystemTime() {
		return System.currentTimeMillis();
	}

	private static class TimeElapsed {

		private String name;
		private long elapsed;

		public TimeElapsed(String name, long elapsed) {
			this.name = name;
			this.elapsed = elapsed;
		}

		public String getName() {
			return name;
		}

		public long getElapsed() {
			return elapsed;
		}
	}
}
